package util.Spliterator;

import java.util.Spliterator;
import java.util.function.Consumer;

/**
 * 字符串中的数字分割迭代计算器实现
 */
public class NumCounterSpliterator implements Spliterator<Character> {

    private String str;
    private int currentChar = 0;

    public NumCounterSpliterator(String str) {
        this.str = str;
        this.currentChar =0;
    }


    @Override
    public boolean tryAdvance(Consumer<? super Character> action) {
      if (currentChar < str.length())
        {
            action.accept(str.charAt(currentChar));
            currentChar++;
            return true;
        }
        return false;
    }
    public void forEachRemaining(Consumer<? super Character > action) {
        for (; currentChar < str.length(); currentChar++) {
            action.accept(str.charAt(currentChar));
        }
    }
    @Override
    public Spliterator<Character> trySplit() {

        int currentSize = str.length() - currentChar;
        if (currentSize < 10)
        {
            return null;
        }
        int pos = currentSize/2 + currentChar ;
        for (;pos < str.length(); pos++){
            if (pos+1 < str.length())
            {
                // 当前Character是数字，且下一个Character不是数字，才需要划分一个新的Spliterator
                Character c = str.charAt(pos);
                if (Character.isDigit(c) && !Character.isDigit(str.charAt(pos+1)) ){
                    String newItem = new String(str.substring(currentChar, pos+1));
                    currentChar = pos+1;
                    return new NumCounterSpliterator(newItem);
                }
                if (!Character.isDigit(c) && Character.isDigit(str.charAt(pos+1))){
                    String newItem = new String(str.substring(currentChar, pos+1));
                    currentChar = pos+1;
                    return new NumCounterSpliterator(newItem);
                }
            }
            else {
                if (Character.isDigit(str.charAt(pos))){
                    Spliterator<Character> spliterator = new NumCounterSpliterator(new String(str.substring(currentChar, pos+1)));
                    currentChar = pos;
                    return spliterator;
                }
            }
        }
        return null;
    }

    @Override
    public long estimateSize() {
        return str.length() - currentChar;
    }

    @Override
    public int characteristics() {
        return ORDERED | SIZED | IMMUTABLE | SUBSIZED;
    }
}

